package com.jd.ty.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import com.jd.ty.dao.AppreciationLogDAO;
import com.jd.ty.dao.CustomerCompanyDAO;
import com.jd.ty.dao.CustomerDAO;
import com.jd.ty.dao.DictionaryDAO;
import com.jd.ty.dao.OrderDAO;
import com.jd.ty.dao.ProjectAttrbuteDAO;
import com.jd.ty.dao.constant.QueryConstants;
import com.jd.ty.dao.util.HqlCriterions;
import com.jd.ty.pojo.Customer;
import com.jd.ty.pojo.CustomerAppreciationLog;
import com.jd.ty.pojo.CustomerCompany;
import com.jd.ty.pojo.CustomerOrder;
import com.jd.ty.pojo.Dictionary;
import com.jd.ty.pojo.OrderTimeComparetor;
import com.jd.ty.pojo.ProjectAttrValue;
import com.jd.ty.pojo.ProjectAttribute;
import com.jd.ty.service.exception.ErrorCode;
import com.jd.ty.service.exception.ErrorMessage;
import com.jd.ty.service.exception.ServiceException;
import com.jd.ty.util.CommonUtils;
import com.jd.ty.util.Pager;

public class CustomerCompanyService {
	private CustomerCompanyDAO customerCompanyDAO;
	private CustomerDAO customerDAO;
	private DictionaryDAO dictionaryDAO;
	private ProjectAttrbuteDAO projectAttrbuteDAO;
	private AppreciationLogDAO logDAO;
	
	@SuppressWarnings("unchecked")
	public List<CustomerCompany> getList(String filter) {
		return customerCompanyDAO.getByQuery(filter);
	}

	public CustomerDAO getCustomerDAO() {
		return customerDAO;
	}

	public void setCustomerDAO(CustomerDAO customerDAO) {
		this.customerDAO = customerDAO;
	}

	@SuppressWarnings("unchecked")
	public List<CustomerCompany> getList(String filter, String sort) {
		return customerCompanyDAO.getByQuery(filter, sort);
	}

	@SuppressWarnings("unchecked")
	public List<CustomerCompany> getList(Pager pager, String filter, String sort) {
		return customerCompanyDAO.getByQuery(pager, filter, sort);
	}

	public CustomerCompany get(long id) {
		return (CustomerCompany) customerCompanyDAO.getById(id);
	}

	public CustomerCompany getFullCompanyInfo(long id) {
		CustomerCompany companyInfo = (CustomerCompany) customerCompanyDAO.getById(id);
		List<CustomerOrder> orders = companyInfo.getCustomerOrders();
		for (CustomerOrder customerOrder : orders) {
			customerCompanyDAO.initialize(customerOrder);
			customerCompanyDAO.initialize(customerOrder.getCustomer());
			customerCompanyDAO.initialize(customerOrder.getEmployee());
			List<ProjectAttrValue> values = customerOrder.getProjectAttrValues();
			for (ProjectAttrValue projectAttrValue : values) {
				customerCompanyDAO.initialize(projectAttrValue);
				customerCompanyDAO.initialize(projectAttrValue.getProjectAttribute());
			}

		}
		List<CustomerAppreciationLog> appreciateLogs = companyInfo.getAppreciationLog();
		for (CustomerAppreciationLog log : appreciateLogs) {
			customerCompanyDAO.initialize(log);
		}
		return companyInfo;
	}

	public void addOrders(long companyId, List<CustomerOrder> orders) {
		CustomerCompany customerCompany = load(companyId);
		for (CustomerOrder customerOrder : orders) {
			Customer customer = (Customer) customerDAO.loadById(customerOrder.getCustomer()
					.getCustomerId());
			customerOrder.setCustomer(customer);
			Dictionary projectType = (Dictionary) dictionaryDAO.getById(customerOrder
					.getProjectType().getDictionaryId());
			customerOrder.setProjectType(projectType);
			List<ProjectAttrValue> values = customerOrder.getProjectAttrValues();
			for (ProjectAttrValue projectAttrValue : values) {
				ProjectAttribute attr = (ProjectAttribute) projectAttrbuteDAO
						.loadById(projectAttrValue.getProjectAttribute().getAttrId());
				projectAttrValue.setProjectAttribute(attr);
			}

		}
		customerCompany.setCustomerOrders(orders);
	}
	
//	public void updateOrder(CustomerCompany customerCompany) {
//		orderDAO.deleteByCompanyId(customerCompany.getCustCompanyId());
//		if (customerCompany.getCustomerOrders()!= null && customerCompany.getCustomerOrders().size() > 0) {
//			for (CustomerOrder customerOrder : customerCompany.getCustomerOrders()) {
//				List<ProjectAttrValue> values = customerOrder.getProjectAttrValues();
//				for (ProjectAttrValue projectAttrValue : values) {
//					projectAttrValue.setCustomerOrder(customerOrder);
//				}
//			}
//			Collections.sort(customerCompany.getCustomerOrders(), new OrderTimeComparetor());
//			customerCompany.setFirstOrderTime(customerCompany.getCustomerOrders().get(0).getDealDate());
//			customerCompany.setLastOrderTime(customerCompany.getCustomerOrders().get(customerCompany.getCustomerOrders().size()-1).getDealDate());
//		}else{
//			customerCompany.setFirstOrderTime(null);
//			customerCompany.setLastOrderTime(null);
//		}
//		logDAO.deleteByCompanyId(customerCompany.getCustCompanyId());
//		if(customerCompany.getAppreciationLog()!=null&&customerCompany.getAppreciationLog().size()>0){
//			List<CustomerAppreciationLog> logs = customerCompany.getAppreciationLog();
//			for (CustomerAppreciationLog customerAppreciationLog : logs) {
//				customerAppreciationLog.setCustomerCompany(customerCompany);
//			}
//		}
//		customerCompanyDAO.merge(customerCompany);
//		
//	}
	public CustomerCompany load(long id) {
		CustomerCompany customerCompany = (CustomerCompany) customerCompanyDAO.loadById(id);
		return customerCompany;
	}

	public void add(final CustomerCompany cc) throws ServiceException {
		HqlCriterions hc = new HqlCriterions();

		hc.and(QueryConstants.CustomerCompany.CUST_COMPANY_NAME, cc.getCustCompanyName(),
				QueryConstants.EQ);

		if (customerCompanyDAO.getCountByQuery(hc.getHqlString()) > 0) {
			String errMsg = CommonUtils.formatString(ErrorMessage.DUPLICATION_ENTITY_DETAIL,
					new String[] { "企业客户记录", cc.getCustCompanyName() });
			throw new ServiceException(ErrorCode.DUPLICATION_ENTITY, errMsg);
		}
		CustomerCompany customerCompany = new CustomerCompany();
		copyProperties(customerCompany, cc);
		customerCompanyDAO.add(customerCompany);

	}

	private void copyProperties(CustomerCompany dist, CustomerCompany src) {
		dist.setCustCompanyName(src.getCustCompanyName());
		dist.setAddress(src.getAddress());
		dist.setFaxNumber(src.getFaxNumber());
		dist.setPhoneNumber(src.getPhoneNumber());
		dist.setPostalCode(src.getPostalCode());

		List<Customer> cs = src.getCustomers();
		List<Customer> csdist = new ArrayList<Customer>();
		for (Customer customer : cs) {

			Customer cust = new Customer();
			if(customer.getCustomerId()!=null){
				cust=(Customer)customerDAO.loadById(customer.getCustomerId());
			}
			cust.setCustomerName(customer.getCustomerName());
			cust.setPhoneNumber(customer.getPhoneNumber());
			cust.setPosition(customer.getPosition());
			cust.setSection(customer.getSection());
			cust.setSex(customer.getSex());
			cust.setEmail(customer.getEmail());
			
			csdist.add(cust);
		}

		for (Customer customer : csdist) {
			customer.linkToCompany(dist);
		}

		dist.setCustomers(csdist);

	}

	public void update(final CustomerCompany cc) throws ServiceException {
		HqlCriterions hc = new HqlCriterions();

		hc.and(QueryConstants.CustomerCompany.CUST_COMPANY_NAME, cc.getCustCompanyName(),
				QueryConstants.EQ);
		hc.and(QueryConstants.CustomerCompany.CUST_COMPANY_ID, cc.getCustCompanyId(),
				QueryConstants.NE);
		if (customerCompanyDAO.getCountByQuery(hc.getHqlString()) > 0) {
			String errMsg = CommonUtils.formatString(ErrorMessage.DUPLICATION_ENTITY_DETAIL,
					new String[] { "企业客户记录", cc.getCustCompanyName() });
			throw new ServiceException(ErrorCode.DUPLICATION_ENTITY, errMsg);
		}
		CustomerCompany customerCompany = (CustomerCompany) customerCompanyDAO.loadById(cc
				.getCustCompanyId());
		processCustomers(customerCompany,cc);
		copyProperties(customerCompany, cc);
		customerCompanyDAO.saveOrUpdate(customerCompany);

	}

	private void processCustomers(CustomerCompany customerCompany,CustomerCompany cc) {
		List<Customer> cus = customerCompany.getCustomers();
		for (int i = cus.size() - 1; i >= 0; i--) {
			Customer customer = cus.get(i);
			boolean isRemoved=true;
			for (Customer customer2 : cc.getCustomers()) {
				if(customer.getCustomerId().equals(customer2.getCustomerId())){
					isRemoved= false;
				}
			}
			if(isRemoved){
				customer.unlinkCompany();
				customerDAO.delete(customer);
			}
		}
	}

	public void setCustomerCompanyDAO(CustomerCompanyDAO customerCompanyDAO) {
		this.customerCompanyDAO = customerCompanyDAO;
	}

	public void delete(Long id) {
		CustomerCompany customerCompany = (CustomerCompany) customerCompanyDAO.loadById(id);
		if (customerCompany != null) {
			customerCompanyDAO.delete(customerCompany);
		}

	}

	public CustomerCompanyDAO getCustomerCompanyDAO() {
		return customerCompanyDAO;
	}
	public Customer getCustomer(Long id){
		return (Customer)customerDAO.getById(id);
	}
	public List<Customer> getCustomersByCompanyId(Long id) {
		HqlCriterions hc = new HqlCriterions();
		hc.and(QueryConstants.Customer.CUST_COMPANY, id, QueryConstants.EQ);
		return customerDAO.getByQuery(hc.getHqlString());
	}

//	public List<CustomerOrder> getOrdersByCompanyId(Long id) {
//		HqlCriterions hc = new HqlCriterions();
//		hc.and(QueryConstants.Order.COMPANY+"."+QueryConstants.CustomerCompany.CUST_COMPANY_ID, id, QueryConstants.EQ);
//		List<CustomerOrder> orders=orderDAO.getByQuery(hc.getHqlString());
//		for (CustomerOrder customerOrder : orders) {
//			orderDAO.initialize(customerOrder.getCustomer());
//			orderDAO.initialize(customerOrder.getEmployee());
//		}
//		return orders;
//	}
//
//	public void setOrderDAO(OrderDAO orderDAO) {
//		this.orderDAO = orderDAO;
//	}

	public void setDictionaryDAO(DictionaryDAO dictionaryDAO) {
		this.dictionaryDAO = dictionaryDAO;
	}

	public void setProjectAttrbuteDAO(ProjectAttrbuteDAO projectAttrbuteDAO) {
		this.projectAttrbuteDAO = projectAttrbuteDAO;
	}

	public void setLogDAO(AppreciationLogDAO logDAO) {
		this.logDAO = logDAO;
	}
}
